﻿$(document).ready(function () {
    var mainDialog = $("#divMainDialog");
    mainDialog.dialog("option", "hide", 'fade');

    //set initial values for DropDownLists
    $("#AlbumSizeId").val($("#AlbumSizeIdValue").val());
    $("#PaperId").val($("#PaperIdValue").val());
    $("#AlbumStatusId").val($("#AlbumStatusIdValue").val());
    $("#AlbumLockStatusId").val($("#AlbumLockStatusIdValue").val());

    //loop through all the preset Album Sections and init the sections
    function InitSections() {
        var AlbumSectionsJSON = $("#AlbumSectionsJSON").val();
        var AlbumSections = $.parseJSON(AlbumSectionsJSON);

        for (var i = 0; i < AlbumSections.length; i++) {
            $("#sectionRowTemplate").tmpl(AlbumSections[i]).appendTo("table#SectionsTable");

            $("table#SectionsTable tr:not(:first)").each(function () {
                var sectionData = $(this).tmplItem().data;

                //set the initial values
                $(this).find("[name$='AlbumSectionStatusId']").val(sectionData.AlbumSectionStatusId);
                $(this).find("[name$='AlbumSectionLockStatusId']").val(sectionData.AlbumSectionLockStatusId);
                $(this).find("[name$='AlbumSectionTypeId']").val(sectionData.AlbumSectionTypeId);
                $(this).find("[name$='SectionTitle']").val(sectionData.SectionTitle);
                $(this).find("[name$='AlbumSectionId']").val(sectionData.AlbumSectionId);
                $(this).find("[name$='EditorPassword']").val(sectionData.EditorPassword);
                $(this).find("[name$='EditorEmail']").val(sectionData.EditorEmail);
                $(this).find("[name$='EditorFirstName']").val(sectionData.EditorFirstName);
                $(this).find("[name$='EditorLastName']").val(sectionData.EditorLastName);
                $(this).find("[name$='EditorPhone']").val(sectionData.EditorPhone);
                $(this).find("[name$='EditorMobile']").val(sectionData.EditorMobile);

                var pagesCount = $(this).find("[name$='PagesCount']");
                pagesCount.val(sectionData.PagesCount).data("value", sectionData.PagesCount);

                var sectionLink = $(this).find(".lnkSection");
                sectionLink.attr("href", sectionLink.data("href") + "/" + sectionData.AlbumSectionId);
            });
        }

        tableAltRows();
    }

    $(".showSectionEditorForm").live("click", function () {
        $(this).parents("tr").next().toggle();

        return false;
    });

    //loop through all the preset Filming Days and init the days
    function InitFilmingDays() {
        var FilmingDaysJSON = $("#FilmingDaysJSON").val();
        var FilmingDays = $.parseJSON(FilmingDaysJSON);

        for (var i = 0; i < FilmingDays.length; i++) {
            $("#filmingDayRowTemplate").tmpl(FilmingDays[i]).appendTo("#FilmingDays");
        }

        if (FilmingDays.length > 0) {
            $("#FilmingDays").show();
            $("#updateFilmingDaysContainer").show();
        }

        //loop through the "photographerId" cells
        $("#FilmingDays td[data-photographer-id]").each(function () {
            //preset the photographer as the value of the DDL
            var photographerId = $(this).data("photographer-id");
            $(this).find("select").val(photographerId);
        });

        setDatepicker();
    }

    InitSections();
    InitFilmingDays();

    /* Update the album details
    -----------------------------*/
    $("#btnUpdateAlbumDetails").click(function () {
        var currentStatus = $("#AlbumStatusId").val();
        var originalStatus = $("#AlbumStatusIdValue").val();

        //if the album status has been updated
        if (currentStatus != originalStatus) {
            var mainDialog = updateDialog("פרטי אלבום", "140", "400");

            //Invoke AJAX method to get the StatusMailConfirm dialog
            $.get(pathPrefix + "Albums/StatusMailConfirm", { "AlbumId": $("#AlbumId").val() }, function (result) {
                mainDialog.html(result);
            }, "html");

            $("#AlbumStatusIdValue").val(currentStatus);
        }
        else {
            UpdateAlbumDetails(false);
        }
    });

    $("#btnUpdateAlbumDetailsWithMail").live("click", function () {
        UpdateAlbumDetails(true);
    });
    $("#btnUpdateAlbumDetailsWithoutMail").live("click", function () {
        UpdateAlbumDetails(false);
    });

    function UpdateAlbumDetails(sendMail) {
        var data = $("#divAlbumDetails :input:not(:hidden)").serializeObject();
        data.AlbumId = $("#AlbumId").val();
        data.NumOfPages = $("#NumOfPages").val();
        data.SendMail = sendMail;

        var mainDialog = updateDialog("פרטי אלבום", "140", "400");

        //Invoke AJAX method to update the album details
        $.post(pathPrefix + "Albums/UpdateAlbumDetails", data, function (result) {
            mainDialog.html(result.Value);

            window.setTimeout(function () {
                closeDialog();
            }, 2000);
        }, "json");
    }

    /*---------------*/

    $("#btnUpdateEditorDetails").click(function () {
        $.validator.unobtrusive.parse($("#divEditorDetails form"));

        if ($("#divEditorDetails form").valid()) {
            var data = $("#divEditorDetails :input").serializeObject();
            data["Album.AlbumId"] = $("#AlbumId").val();

            var mainDialog = updateDialog("פרטי עורך", "140", "400");

            //Invoke AJAX method to update the album's editor details
            $.post(pathPrefix + "Albums/UpdateAlbumEditorDetails", data, function (result) {
                mainDialog.html(result.Value);

                window.setTimeout(function () {
                    closeDialog();
                }, 2000);
            }, "json");
        }
    });

    $("#btnUpdateStudioNotes").click(function () {
        var data = {
            "id": $("#AlbumId").val(),
            "studioNotes": $("#StudioNotes").val()
        };

        var mainDialog = updateDialog("הערות סטודיו", "140", "400");

        //Invoke AJAX method to update the album's studio notes
        $.post(pathPrefix + "Albums/UpdateStudioNotes", data, function (result) {
            mainDialog.html(result.Value);

            window.setTimeout(function () {
                closeDialog();
            }, 2000);
        }, "json");
    });

    $("#btnUpdateFilmingDays").click(function () {
        var mainDialog = updateDialog("ימי צילום", "140", "400");

        var data = {
            "id": $("#AlbumId").val(),
            "filmingDays": new Array()
        };

        $("#FilmingDays tr:not(:first)").each(function () {
            var filmingDayData = $(this).find(":input").serializeObject();

            //add the object data to the JSON object
            if (filmingDayData.Date != "") {
                data.filmingDays.push(filmingDayData);
            }
        });

        //Invoke AJAX method to update the album's filming days
        $.ajax({
            url: pathPrefix + "Albums/UpdateFilmingDays",
            data: JSON.stringify(data),
            type: "POST",
            dataType: "json",
            contentType: 'application/json; charset=utf-8',
            success: function (result) {
                mainDialog.html(result.Value);

                window.setTimeout(function () {
                    closeDialog();
                }, 2000);
            }
        });
    });

    function CalculateSpineWidth() {
        var data = {
            "AlbumId": $("#AlbumId").val(),
            "PaperId": $("#PaperId").val()
        };

        $("#spineWidthMm").html("");

        //Invoke AJAX method to calculate the spine width after this Paper change
        $.get(pathPrefix + "Albums/CalculateSpineWidth", data, function (result) {
            $("#spineWidthMm").html("רוחב שדרה: " + result.toFixed(2) + " מ\"מ");
        }, "json");
    }

    //when the user change the paper type of this album
    $("#PaperId").change(CalculateSpineWidth);

    CalculateSpineWidth();

    /*Print Versions
    -----------------*/

    $("#btnUpdatePrintVersions").click(function () {
        var mainDialog = updateDialog("גרסאות דפוס", "140", "400");

        var data = {
            "id": $("#AlbumId").val(),
            "printVersions": new Array()
        };

        $("#PrintVersions tr:not(:first)").each(function () {
            var printVersionData = $(this).find(":input").serializeObject();

            //add the object data to the JSON object
            if (printVersionData.AlbumPrintVersionId != "") {
                data.printVersions.push(printVersionData);
            }
        });

        //Invoke AJAX method to update the album's print versions
        $.ajax({
            url: pathPrefix + "Albums/UpdatePrintVersions",
            data: JSON.stringify(data),
            type: "POST",
            dataType: "json",
            contentType: 'application/json; charset=utf-8',
            success: function (result) {
                mainDialog.html(result.Value);

                window.setTimeout(function () {
                    closeDialog();
                }, 2000);
            }
        });
    });

    $(".removePrintVersion").live("click", function () {
        //remove the selected row
        $(this).parents("tr").remove();

        if ($("#PrintVersions tr").length == 1) {
            $("#PrintVersions").hide();
        }

        return false;
    });

    $(".IsSent").live("click", function () {
        var isChecked = $(this).prop("checked");
        var textbox = $(this).siblings("input[type=text]");

        //show or hide the relevat textbox
        if (isChecked) {
            textbox.show();
            textbox.val($("#CurrentDate").val());
        }
        else {
            textbox.hide();
            textbox.val("");
        }
    });

    $(".ShowToAlbumEditor").live("click", function () {
        var isChecked = $(this).prop("checked");
        var hidden = $(this).siblings("[name='ShowToAlbumEditor']");

        hidden.val(isChecked);
    })

    /*--------------------*/

    $("#btnUpdateAlbumSections").click(function () {
        var rowsDeleted = $("#SectionsTable").data("RowsDeleted");
        var sectionsWithPagesDecrease = $("[name='PagesCount'].pagesDecrease").length;

        //if there are sections with pages descrease
        if (sectionsWithPagesDecrease > 0 || rowsDeleted == true) {
            openConfirmDialog("השינוי שביצעת יגרום למחיקת עמודים באלבום.<br />האם אתה בטוח שברצונך לבצע את העדכון?", function () {
                var mainDialog = updateDialog("מקטעים", "140", "400");
                UpdateAlbumSections();
            });
        }
        else {
            var mainDialog = updateDialog("מקטעים", "140", "400");
            UpdateAlbumSections();
        }
    });

    function UpdateAlbumSections() {
        var data = {
            "id": $("#AlbumId").val(),
            "sections": new Array()
        };

        var rows = $("table#SectionsTable tr:not(:first):not(.editorFormRow)");
        rows.each(function () {
            var sectionElements = $(this).find(":input");
            var sectionEditorElements = $(this).next(".editorFormRow").find(":input");

            var sectionData = sectionElements.add(sectionEditorElements).serializeObject();

            //add the section to the JSON object
            if (sectionData.SectionTitle != "" && sectionData.EditorPassword != "" && sectionData.AlbumSectionTypeId != "") {
                data.sections.push(sectionData);
            }
        });

        //check how many pagesCount are invalid (odd numbers)
        var invalisPagesNumber = 0;
        rows.each(function () {
            if ($(this).find("[name=PagesCount]:visible").length > 0) {
                var pagesCount = parseInt($(this).find("[name=PagesCount]").val());

                if (pagesCount % 2 != 0 || pagesCount < 2) {
                    invalisPagesNumber++;
                }
            }
        });

        var mainDialog = $("#divMainDialog");

        if (data.sections.length > 0) {
            if (invalisPagesNumber == 0) {
                //Invoke AJAX method to update the album's sections
                $.ajax({
                    url: pathPrefix + "Albums/UpdateAlbumSections",
                    data: JSON.stringify(data),
                    type: "POST",
                    dataType: "json",
                    contentType: 'application/json; charset=utf-8',
                    success: function (result) {
                        mainDialog.html(result.Value);

                        CalculateSpineWidth();

                        window.setTimeout(function () {
                            closeDialog();
                        }, 2000);
                    }
                });
            }
            else {
                mainDialog.html("מספר העמודים בכל מקטע חייב להיות זוגי.");
            }
        }
        else {
            mainDialog.html("לא הוגדרו מקטעים באלבום זה.");
        }
    }

    $("#btnSendForApproval").click(function () {
        openConfirmDialog("האם אתה בטוח?", function () {
            var data = {
                "id": $("#AlbumId").val(),
                "statusId": 5
            };

            var mainDialog = updateDialog("אישור אלבום", "140", "400");

            //Invoke AJAX method to change the album status
            $.post(pathPrefix + "Albums/ChangeAlbumStatus", data, function (result) {
                mainDialog.html(result.Value);
            }, "json");
        });

        return false;
    });

    function CheckPagesCountValid() {
        //sum all the pages of sections
        var totalPagesOfSections = 0;
        $("[name='PagesCount']:visible").each(function () {
            totalPagesOfSections += parseInt($(this).val());
        });

        var albumPages = parseInt($("#NumOfPages").html());

        //check if the SectionsPages is the same as the AlbumPages
        return (albumPages == totalPagesOfSections);
    }

    $("#btnSendMailToAlbumEditor").click(function () {
        var editorEmail = $("#Album_EditorEmail").val();

        openConfirmDialog("האם אתה בטוח שברצונך לשלוח מייל עם סיסמאות הפרויקט לעורך האלבום " + editorEmail + "?", function () {
            var mainDialog = updateDialog("שליחת מייל", "120", "300");

            var data = { "AlbumId": $("#AlbumId").val() };

            //Invoke AJAX method to send mail to the album editor
            $.post(pathPrefix + "Albums/SendMailToAlbumEditor", data, function (result) {
                mainDialog.html(result.Value);

                window.setTimeout(function () {
                    closeDialog();
                }, 2000);
            }, "json");
        });

        return false;
    });

    //when the user change the Album Status
    $("#AlbumStatusId").change(function () {
        ShowHideDeleteFilesButton();
    });
    ShowHideDeleteFilesButton();

    function ShowHideDeleteFilesButton() {
        var currentAlbumStatus = $("#AlbumStatusId").val();

        //if the current status of album is "הושלם"
        if (currentAlbumStatus == "6") {
            $("#btnDeleteAlbumFiles").show();
        }
        else {
            $("#btnDeleteAlbumFiles").hide();
        }
    }

    //when the user change the Album LockStatus
    $("#AlbumLockStatusId").change(function () {
        var albumLockStatus = $(this).siblings("#AlbumLockStatusIdValue").val();
        var newLockStatus = $(this).val();

        //if the current lockStatus is "Locked" and the updated lockStatus is "Open"
        if (albumLockStatus == "1" && newLockStatus == "2") {
            //change the status to "בעריכה"
            var row = $(this).parents("tr");
            $(this).parents("#divAlbumDetails").find("#AlbumStatusId").val("3");

            //change the sections's lock status to "פתוח לעריכה"
            $("[name='AlbumSectionLockStatusId']").val("3");
        }
    });

    $("[name='AlbumSectionLockStatusId']").live("change", function () {
        var albumSectionRow = $(this).parents("tr");
        var lockStatusId = $(this).val();

        //if lockStatus = "פתוח לעריכה"
        if (lockStatusId == "3") {
            //change status to "לא מאושר"
            albumSectionRow.find("[name='AlbumSectionStatusId']").val("1").change();
        }
    });

    $("[name='PagesCount']").live("change", function () {
        var originalValue = parseInt($(this).data("value"));
        var currentValue = parseInt($(this).val());

        //check if the user decreased the pagesCount
        if (currentValue < originalValue) {
            $(this).addClass("pagesDecrease");
            $(this).siblings(".pagesDecreaseWarning").css("visibility", "visible");
        }
        else {
            $(this).removeClass("pagesDecrease");
            $(this).siblings(".pagesDecreaseWarning").css("visibility", "hidden");
        }

        if (CheckPagesCountValid() == false) {
            $("#pagesCountNotEqual").show();
        }
        else {
            $("#pagesCountNotEqual").hide();
        }
    });

    $("#SectionLockStatusForAll").change(function () {
        var lockStatusSelector = $(this);
        var lockStatus = lockStatusSelector.val();

        if (lockStatus != "") {
            openConfirmDialog("האם אתה בטוח שברצונך לעדכן את מצב הנעילה של כל המקטעים?", function () {
                //change the lock status for all sections
                $("[name$='AlbumSectionLockStatusId']").val(lockStatus);
            });

            lockStatusSelector.val("");
        }
    });

    /* Contract PDF
    -------------------*/

    //get the contract PDF file (if there is one)
    $.post(pathPrefix + "Albums/GetContractPDF/" + $("#AlbumId").val(), null, function (result) {
        $("#divUploadContract").show();

        //if there is no file
        if (result == "") {
            $("#divContractFile").hide();
        }
        else {
            $("#divContractFile").show();
            $("#divContractFile a").attr("href", result);
            $("#divUploadContract a").html("החלף");
        }
    }, "json");

    $("#divUploadContract a").click(function () {
        return false;
    });

    //upload the selected PDF file
    $("#ContractPdfFile").change(function () {
        var contractPdf = $(this).val();

        if (contractPdf != "") {
            var form = $(this).parents("form");
            form.submit();
        }
    });

    /* Approval PDF
    -------------------*/

    $(".showApprovalFileDialog").live("click", function () {
        var mainDialog = updateDialog("קובץ אישור", "150", "350");
        var rowData = $(this).tmplItem().data;

        var data = { "AlbumPrintVersionId": rowData.AlbumPrintVersionId };

        //Invoke AJAX method to show the approval file dialog
        $.get(pathPrefix + "Albums/ApprovalFile", data, function (result) {
            mainDialog.html(result);
        }, "html");

        return false;
    });

    $("#approvalFileDialog .uploadApprovalFile a").live("click", function () {
        return false;
    });

    //when the user select file - upload the selected PDF file
    $("#approvalFileDialog [name='ApprovalPdfFile']").live("change", function () {
        if ($(this).val() != "") {
            var form = $(this).parents("form");
            form.submit();
        }
    });

    /*-------------------*/

    $(".lnkDeletePDFfiles").live("click", function () {
        var deleteButton = $(this);

        var data = {
            "AlbumId": $("#AlbumId").val(),
            "InnerFileName": $(this).data("inner-file"),
            "CoverFileName": $(this).data("cover-file")
        };

        openConfirmDialog("האם אתה בטוח?", function () {
            //Invoke AJAX method to delete the pdf files
            $.post(pathPrefix + "Pdf/DeleteFiles", data, function () {
                //InitPrintVersions();
            }, "json");
        });

        return false;
    });

    /*Album Files
    --------------*/

    $("#btnViewAlbumFiles").click(function () {
        var mainDialog = updateDialog("קבצי הפרויקט", "250", "350");

        //Invoke AJAX method to show the AlbumFiles dialog
        $.get(pathPrefix + "Albums/AlbumFiles", { "AlbumId": $("#AlbumId").val() }, function (result) {
            mainDialog.html(result);

            tableAltRows();
        }, "html");

        return false;
    });

    $("#btnSendMsgMailToAllEditors").click(function () {

        var mainDialog = updateDialog("שלח הודעה לכל העורכים", "250", "350");

        //Invoke AJAX method to show the AlbumFiles dialog
        $.get(pathPrefix + "Albums/MailMsgDialog", null, function (result) {
            mainDialog.html(result);
        }, "html");

        return false;
    });

    $("#btnSendMessageText").live("click", function () {
        // Disable the button
        var btn = $(this);
        var oldValue = btn.val();
        btn.attr("disabled", "disabled").addClass("disabled");
        btn.val("מתבצעת שליחה..");

        var data = {
            "AlbumId": $("#AlbumId").val(),
            "MessageText": $("#messageText").val()
        };

        $.post(pathPrefix + "Mail/SendMsgToAllEditors", data, function (result) {

            // Enable Button
            btn.val(oldValue);
            btn.removeAttr("disabled").removeClass("disabled");    

            mainDialog.html(result);
        }, "json");
    });

    $("#btnDeleteAlbumFiles").click(function () {
        var mainDialog = updateDialog("ריקון קבצי הפרויקט", "200", "550");

        //Invoke AJAX method to show the delete AlbumFiles dialog
        $.get(pathPrefix + "Albums/DeleteAlbumFiles", { "AlbumId": $("#AlbumId").val() }, function (result) {
            mainDialog.html(result);

            var directorySize = $("#directorySize").html();
            mainDialog.find("#albumDirectorySize").html(directorySize);
        }, "html");

        return false;
    });

    $("#btnDeleteFilesConfirm").live("click", function () {
        /*var data = $("#DeleteFilesForm :input").serialize();

        if ($("#DeleteFilesForm :checkbox:checked").length > 0) {
        }*/
        openConfirmDialog("האם אתה בטוח שברצונך לרוקן את קבצי הפרויקט?<br />לא ניתן יהיה לשחזר את הקבצים שיימחקו.", function () {

            var data = { "AlbumId": $("#AlbumId").val(), "Delete": true };

            //Invoke AJAX method to delete the album files
            $.post(pathPrefix + "Albums/DeleteAlbumFiles", data, function (result) {
                var mainDialog = updateDialog("מחיקת קבצי הפרויקט", "250", "350");
                mainDialog.html("קבצי הפרויקט רוקנו בהצלחה!<br />כעת לא ניתן יהיה לעדכן את עיצוב האלבום ולצפות בו בממשק העיצוב.<br />ניתן יהיה להמשיך לצפות בנתוני הפרויקט בעמוד זה, ובגרסת הדפוס האחרונה שלו.");

                window.setTimeout(function () {
                    window.location = window.location;
                }, 3000);
            }, "json");
        });
    });

    /*------------*/
});